import { Injectable } from '@nestjs/common';
import { CreateGenerativeAIAchievementDto } from './dto/create-generative-ai-achievement.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { GenerativeAIAchievement } from './entities/generative-ai-achievement.entity';
import { Repository } from 'typeorm';
import { Response } from 'express';
import * as path from 'path';
import * as fs from 'fs';
import { promises as fsPromises } from 'fs';
import { FileUtil } from 'src/common/file';

@Injectable()
export class GenerativeAiAchievementService {
  constructor(
    @InjectRepository(GenerativeAIAchievement)
    private readonly generativeAIAchievementRepository: Repository<GenerativeAIAchievement>,
  ) {}
  async uploadAchievementItem(
    createGenerativeAIAchievementDto: CreateGenerativeAIAchievementDto,
    file: any,
  ) {
    createGenerativeAIAchievementDto.file_name = file.filename;
    createGenerativeAIAchievementDto.src = file.filename;
    createGenerativeAIAchievementDto.original_name = Buffer.from(
      file.originalname,
      'latin1',
    ).toString('utf8');
    createGenerativeAIAchievementDto.size = String(file.size);
    createGenerativeAIAchievementDto.raw_type = file.mimetype;
    createGenerativeAIAchievementDto.folder = '-1';

    if (file.mimetype.startsWith('image/')) {
      createGenerativeAIAchievementDto.type = 'picture';
    } else if (file.mimetype.startsWith('audio/')) {
      createGenerativeAIAchievementDto.type = 'audio';
    } else if (file.mimetype.startsWith('video/')) {
      createGenerativeAIAchievementDto.type = 'video';
    }

    const insertRes = await this.generativeAIAchievementRepository.insert(
      this.generativeAIAchievementRepository.create(
        createGenerativeAIAchievementDto,
      ),
    );
    return (insertRes.raw[0] as any).id;
  }
  getAllAchievement() {
    return this.generativeAIAchievementRepository.find();
  }
  getAchievementById(id: string) {
    return this.generativeAIAchievementRepository.findOne({
      where: { id: id },
    });
  }

  getAchievementByType(type: string) {
    return this.generativeAIAchievementRepository.find({
      where: { type: type },
    });
  }

  async deleteAchievementById(id: string) {
    // 执行删除逻辑
    const fileItem = await this.generativeAIAchievementRepository.findOne({
      where: { id: id },
    });
    try {
      const result = await this.generativeAIAchievementRepository.delete({
        id: id,
      });
      // 判断
      const fileList = await this.generativeAIAchievementRepository.find({
        where: {
          src: fileItem.src,
        },
      });
      if (fileList.length === 0) {
        let folder = 'other'; // 默认文件夹名
        if (fileItem.raw_type.startsWith('image/')) {
          if (fileItem.raw_type === 'image/tiff') {
            folder = 'imageraster';
          } else {
            folder = 'image';
          }
        } else if (fileItem.raw_type.startsWith('audio/')) {
          folder = 'audio';
        } else if (fileItem.raw_type.startsWith('video/')) {
          folder = 'video';
        } else if (fileItem.raw_type.startsWith('text/')) {
          folder = 'text';
        } else if (fileItem.raw_type.startsWith('application/')) {
          folder = 'application';
        }
        const fileName = path.resolve(
          process.env.FILE_PATH +
            '/' +
            'GenerativeAI' +
            '/' +
            folder +
            '/' +
            fileItem.src,
        );
        if (result.affected && result.affected > 0) {
          await FileUtil.deleteLocalFile(fileName);
          if (folder === 'imageraster') {
            const imagerasterPath = path.resolve(
              `${process.env.FILE_PATH}/${
                fileItem.uploader
              }/imagerasterTopng/${fileItem.src.replace('.tif', '.png')}`,
            );
            await FileUtil.deleteLocalFile(imagerasterPath);
          }
          return `成功删除 ${result.affected} 条记录`;
        } else {
          return `未找到匹配的记录，没有进行删除操作`;
        }
      }
    } catch (err) {
      console.error('删除记录失败', err);
      throw '删除记录失败';
    }
  }

  async getFileItemContent(
    id: string,
    response: Response<any, Record<string, any>>,
  ) {
    const res = await this.generativeAIAchievementRepository.findOne({
      where: { id: id },
    });
    if (res) {
      let folder = '';
      if (res.raw_type.startsWith('image/')) {
        if (res.raw_type === 'image/tiff') {
          folder = 'imagerasterTopng';
          res.raw_type = 'image/png';
        } else {
          folder = 'image';
        }
      } else if (res.raw_type.startsWith('audio/')) {
        folder = 'audio';
      } else if (res.raw_type.startsWith('video/')) {
        folder = 'video';
      } else if (res.raw_type.startsWith('text/')) {
        folder = 'text';
      } else if (res.raw_type.startsWith('application/')) {
        folder = 'application';
      }
      const destinationPath = path.resolve(
        `${process.env.FILE_PATH}/GenerativeAI/${folder}/${res.src.replace(
          '.tif',
          '.png',
        )}`,
      );
      const stats = await fsPromises.stat(destinationPath);
      response.setHeader('Content-Type', res.raw_type);
      response.setHeader('Content-Length', stats.size.toString());
      response.setHeader('Accept-Ranges', 'bytes');

      const fileStream = fs.createReadStream(destinationPath);
      fileStream.pipe(response);
    }
  }

  async downloadAIProductionItemStream(
    id: string,
    response: Response<any, Record<string, any>>,
  ) {
    try {
      const res = await this.generativeAIAchievementRepository.findOne({
        where: { id: id },
      });
      if (!res) {
        throw new Error('File not found');
      }

      let folder = 'other';
      if (res.raw_type.startsWith('image/')) {
        folder = res.raw_type === 'image/tiff' ? 'imageraster' : 'image';
      } else if (res.raw_type.startsWith('audio/')) {
        folder = 'audio';
      } else if (res.raw_type.startsWith('video/')) {
        folder = 'video';
      } else if (res.raw_type.startsWith('text/')) {
        folder = 'text';
      } else if (res.raw_type.startsWith('application/')) {
        folder = 'application';
      }

      const filePath = path.resolve(
        `${process.env.FILE_PATH}/GenerativeAI/${folder}/${res.src}`,
      );

      // Set appropriate headers
      response.setHeader('Content-Type', res.raw_type);
      response.setHeader(
        'Content-Disposition',
        `attachment; filename="${encodeURIComponent(res.src)}"`,
      );

      // Stream the file directly
      const fileStream = fs.createReadStream(filePath);
      fileStream.pipe(response);
    } catch (err) {
      console.error('下载记录失败', err);
      response.status(500).send('下载记录失败');
    }
  }
}
